package com.zone.api.http

import kotlinx.coroutines.*

/**
 *Author: last
 *Time: 2024-1-13
 *Description: xxx
 */
typealias ErrorHandle = (Throwable) -> Boolean
typealias CoroutineLambda = suspend CoroutineScope.() -> Unit

private fun request(block: CoroutineLambda) {
    val exceptionHandle = CoroutineExceptionHandler { coroutineContext, throwable ->
        throwable.printStackTrace()
    }
    GlobalScope.launch(exceptionHandle) {
        withContext(Dispatchers.Main) {
            block()
        }
    }
}

fun httpRequest(
    error: ErrorHandle? = null,
    block: CoroutineLambda
) {
    request {
        try {
            block()
        } catch (e: Exception) {
            e.printStackTrace()
            error?.invoke(e)
        }
    }
}
